<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\common\library\Refund;
use app\common\model\modify\Address as ModifyAddress;
use app\common\model\modify\Order;
use app\common\model\modify\Category;
use app\common\model\modify\Modify as ModifyModify;
use app\common\model\modify\Review;
use app\common\model\user\Address;
use think\Db;
use think\Exception;
use think\Validate;

/**
 * 改装接口
 */
class Modify extends Api
{
    protected $noNeedLogin = ['category', 'lists', 'info'];
    protected $noNeedRight = ['*'];

    /**
     * @Author LK
     * @ApiTitle (改装分类)
     * @ApiMethod (GET)
     * @ApiReturnParams (name="code", type="integer", required=true, description="")
     * @ApiReturn ({'code':1,'msg':'返回成功'})
     */
    public function category()
    {
        $list = Category::all(['pid' => 0]);
        $this->success('请求成功', $list);
    }

    /**
     * @Author LK
     * @ApiTitle (改装列表)
     * @ApiMethod (GET)
     * @ApiParams (name="first_id", type="integer", required=true, sample="", description="一级分类")
     * @ApiParams (name="two_id", type="integer", required=true, sample="", description="二级分类")
     * @ApiParams (name="keywords", type="string", required=true, sample="", description="关键字")
     * @ApiReturnParams (name="code", type="integer", required=true, description="")
     * @ApiReturn ({'code':1,'msg':'返回成功'})
     */
    public function lists()
    {
        $param = request()->param();
        extract($param);
        $model = new ModifyModify();
        if (isset($keywords) && $keywords) {
            $model->whereLike('title', $keywords);
        }
        if ($first_id && $two_id) {
            $model->where('c_id', $two_id);
        }
        if ($first_id && !$two_id) {
            // $cate_ids = Category::whereIn('pid', $first_id)->column('id');
            $model->where('f_id', $first_id);
        }
        $lists = $model->order('id desc')->paginate();
        $this->success('请求成功', $lists);
    }


    /**
     * @Author LK
     * @ApiTitle (改装详情)
     * @ApiMethod (GET)
     * @ApiParams (name="id", type="integer", required=true, sample="", description="id")
     * @ApiReturnParams (name="code", type="integer", required=true, description="")
     * @ApiReturn ({'code':1,'msg':'返回成功'})
     */
    public function info()
    {
        $param = request()->param();
        extract($param);
        $data = ModifyModify::get($id);
        $this->success('', $data);
    }
    /**
     * @Author LK
     * @ApiTitle (改装下单)
     * @ApiMethod (POST)
     * @ApiParams (name="id", type="integer", required=true, sample="", description="ID")
     * @ApiParams (name="num", type="integer", required=true, sample="", description="购买数量")
     * @ApiParams (name="deliver", type="integer", required=true, sample="", description="配送方式:1=快递到家,2=到店改装")
     * @ApiParams (name="address_id", type="integer", required=fasle, sample="", description="收货地址")
     * @ApiParams (name="server_id", type="integer", required=fasle, sample="", description="服务地址")
     * @ApiParams (name="mark", type="string", required=fasle, sample="", description="备注")
     * @ApiReturnParams (name="code", type="integer", required=true, description="")
     * @ApiReturn ({'code':1,'msg':'返回成功'})
     */
    public function addOrder()
    {
        $param = request()->param();
        extract($param);
        if (!isset($id) || !$id) {
            $this->error('参数错误');
        }
        $data = ModifyModify::get($id);
        $data->hidden(['id']);
        if (!$data) {
            $this->error('产品不存在');
        }
        if ($data['stock'] < $num) {
            $this->error('库存不足');
        }
        Db::startTrans();
        try {
            $data = $data->toArray();
            $data['m_id'] = $id;
            $data['num'] = $num;
            $data['sn'] = sn('lease_order', 'sn', 'MD');
            $data['user_id'] = $this->auth->id;
            $data['deliver'] = $deliver;
            $data['mark'] = $mark;
            $data['createtime'] = time();

            if ($deliver == 1) {
                if (isset($address_id) && !empty($address_id)) {
                    $addressInfo = Address::get($address_id);
                } else {
                    $addressInfo = Address::getDefaultAddress($user_id);
                }
                if ($addressInfo) {
                    $data['contact']  = $addressInfo['contact'];
                    $data['telephone']  = $addressInfo['telephone'];
                    $data['address_id']  = $addressInfo['id'];
                    $data['address']  = $addressInfo['province'] . $addressInfo['city'] . $addressInfo['area'] . $addressInfo['address'];
                } else {
                    exception('请选择收货地址');
                }
            } else {
                $data['server_id']  = $server_id;
            }
            $order = new Order();

            $res = $order->allowField(true)->save($data);
            if ($res) {
                ModifyModify::where('id', $id)->dec('stock', $num)->update();
            }
            queue('app\common\job\ModifyOrder', $order->id, 300, '1255ModifyOrder');
            Db::commit();
            $this->success('下单成功', $order->id);
        } catch (Exception $th) {
            Db::rollback();
            $this->error('下单失败', $th);
        }
    }
    /**
     * @Author LK
     * @ApiTitle (改装订单)
     * @ApiMethod (GET)
     * @ApiParams (name="status", type="integer", required=true, sample="", description="改装状态:all=全部,0=待支付,1=待改装/已支付,2=待收货,3=已改装/已完成")
     * @ApiReturnParams (name="code", type="integer", required=true, description="")
     * @ApiReturn ({'code':1,'msg':'返回成功'})
     */
    public function order_list()
    {

        $param = request()->param();
        extract($param);
        $model = new Order();
        if ($status != 'all') {
            $model->where('status', $status);
        }
        if ($status == '3') {
            $model->where('status', '>', '2');
        }
        $lists = $model->with('address')->where('user_id', $this->auth->id)->where('status', '<>', '-1')->order('id desc')->paginate();
        $this->success('', $lists);
    }
    /**
     * @Author LK
     * @ApiTitle (确认订单)
     * @ApiMethod (POST)
     * @ApiParams (name="id", type="integer", required=true, sample="", description="ID")
     * @ApiReturnParams (name="code", type="integer", required=true, description="")
     * @ApiReturn ({'code':1,'msg':'返回成功'})
     */
    public function take_order()
    {
        $param = request()->param();
        extract($param);
        if (!isset($id) || !$id) {
            $this->error('参数错误');
        }
        $order = Order::get(['id' => $id, 'user_id' => $this->auth->id]);
        if (!$order) {
            $this->error('订单不存在');
        }
    
        $order->status = '3';
        $order->taketime = time();
        $res = $order->save();
        if ($res) {
            $this->success('成功');
        }
        $this->error('失败');
    }
    /**
     * @Author LK
     * @ApiTitle (取消退款订单)
     * @ApiMethod (POST)
     * @ApiParams (name="id", type="integer", required=true, sample="", description="ID")
     * @ApiParams (name="reason", type="integer", required=true, sample="", description="取消原因")
     * @ApiReturnParams (name="code", type="integer", required=true, description="")
     * @ApiReturn ({'code':1,'msg':'返回成功'})
     */
    public function cancel_order()
    {
        $param = request()->param();
        extract($param);
        if (!isset($id) || !$id) {
            $this->error('参数错误');
        }
        Db::startTrans();
        try {
            $order = Order::get($id);
            if ($order->status == 0) {
                Order::where('id', $order['id'])->where('status', '0')->update(['status' => '-1', 'reason' => $reason]);
                ModifyModify::where('id', $order['m_id'])->inc('stock', $order['num'])->update();
            } else {
                Order::where('id', $order['id'])->update(['cancel_status' => '1', 'reason' => $reason]);

                // $res = Refund::refund($order->sn, $order->pay_price);
                // if ($res == true) {
                //     $order->status = '-1';
                //     $order->save();
                // } else {
                //     exception('退款失败');
                // }
            }
            // ModifyModify::where('id', $order['m_id'])->inc('stock', $order['num'])->update();
            Db::commit();
        } catch (\Exception $th) {
            Db::rollback();
            $this->error($th->getMessage());
        }
        $this->success('');
    }
    /**
     * @Author LK
     * @ApiTitle (改装订单详情)
     * @ApiMethod (GET)
     * @ApiParams (name="id", type="integer", required=true, sample="", description="ID")
     * @ApiReturnParams (name="code", type="integer", required=true, description="")
     * @ApiReturn ({'code':1,'msg':'返回成功'})
     */
    public function order_info()
    {
        $param = request()->param();
        extract($param);
        $data = Order::get($id, ['address', 'userAddress']);
        $this->success('', $data);
    }
    /**
     * @Author LK
     * @ApiTitle (改装地址)
     * @ApiMethod (GET)
     * @ApiReturnParams (name="code", type="integer", required=true, description="")
     * @ApiReturn ({'code':1,'msg':'返回成功'})
     */
    public function addressList()
    {
        $lists = ModifyAddress::all();
        $this->success('', $lists);
    }
    /**
     * @Author LK
     * @ApiTitle (改装订单评论)
     * @ApiMethod (POST)
     * @ApiParams (name="order_id", type="integer", required=true, sample="", description="订单id")
     * @ApiParams (name="goods_id", type="integer", required=true, sample="", description="商品id")
     * @ApiParams (name="star", type="integer", required=true, sample="", description="星级")
     * @ApiParams (name="content", type="string", required=true, sample="", description="评论内容")
     * @ApiParams (name="images", type="string", required=true, sample="", description="评论图片")
     * @ApiReturnParams (name="code", type="integer", required=true, description="")
     * @ApiReturn ({'code':1,'msg':'返回成功'})
     */
    public function review()
    {
        $param = request()->param();
        extract($param);
        $validate = new Validate(
            [
                'order_id' => 'require|gt:0',
                'goods_id' => 'require|gt:0',
                'star' => 'require|gt:0',
                'content' => 'require',
            ],
            [
                'order_id.require' => '参数错误',
                'goods_id.require' => '参数错误',
                'star.require' => '请星级打分',
                'content.require' => '请输入评论内容',
            ]
        );
        $result = $validate->check($param);
        if (!$result) {
            $this->error(__($validate->getError()));
        }
        $model = new  Review();
        $order = Order::get($order_id);
        $order->status = '4';
        $param['user_id'] = $this->auth->id;
        $res = $model->allowField(true)->save($param);
        if ($res) {
            $order->save();
            $this->success('成功');
        }
        $this->error('失败');
    }
    /**
     * @Author LK
     * @ApiTitle (评论列表)
     * @ApiMethod (GET)
     * @ApiParams (name="id", type="integer", required=true, sample="", description="ID")
     * @ApiParams (name="limit", type="integer", required=true, sample="", description="每页数量")
     * @ApiReturnParams (name="code", type="integer", required=true, description="")
     * @ApiReturn ({'code':1,'msg':'返回成功'})
     */
    public function review_list()
    {
        $param = request()->param();
        extract($param);
        if (!isset($id) || !$id) {
            $this->error('参数错误');
        }
        $lists = Review::with('user')->where('goods_id', $id)->where('state', '2')->order('id desc')->paginate($limit ?? 10);
        $this->success('', $lists);
    }
}
